package com.cyandpos.pad.activity;


import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.changyi.device.APApplication;
import com.changyi.device.printer.PrintManagerLib;
import com.cyandpos.pad.R;
import com.cyandpos.pad.common.commondata.Constant;
import com.cyandpos.pad.common.commondata.ConstantString;
import com.cyandpos.pad.common.commondata.DialogConstant;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.commondata.OnDialogListener;
import com.cyandpos.pad.common.commondata.SktConfigIdCrmConstant;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.common.swipemanager.SwipeCardCommon;
import com.cyandpos.pad.common.ticketformat.TicketFormat;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.offline.offlinedb.OfflineManager;
import com.cyandpos.pad.pickhangup.SaveHangUpCallBack;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.Member;
import com.cyandpos.pad.posdata.Person;
import com.cyandpos.pad.posdata.PromationoodInfo;
import com.cyandpos.pad.posdata.QueryGoodParam;
import com.cyandpos.pad.posdata.QueryMemberReq;
import com.cyandpos.pad.posdata.SubTicketItem;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.presentation.AdPresentationUtil;
import com.cyandpos.pad.sale.adapter.DefaultGoodAdapter;
import com.cyandpos.pad.sale.adapter.ExchangeGoodBillInfoListAdapter;
import com.cyandpos.pad.sale.adapter.GoodsListAdapter;
import com.cyandpos.pad.sale.presenter.SalePresenterImpl;
import com.cyandpos.pad.sale.saleutils.SaleUtil;
import com.cyandpos.pad.sale.saleutils.TimeThread;
import com.cyandpos.pad.sale.view.ISaleView;
import com.cyandpos.pad.sale.view.SelfNumKeyView;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.PayUtil;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.LogUtils;
import com.cyandpos.pad.utils.log.SDTools;
import com.cyandpos.pad.utils.view.InputNumberDialogCommon;
import com.google.gson.JsonObject;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
public class MainActivity extends BaseActivity implements ISaleView , SelfNumKeyView.SelfNumCallBack , SwipeCardCommon.DoAfterSwipeCard{

    @BindView(R.id.tv_main_title_version)
    TextView tvMainTitleVersion;
    @BindView(R.id.tv_main_title_cashier)
    TextView tvMainTitleCashier;
    @BindView(R.id.tv_main_title_sktno)
    TextView tvMainTitleSktno;
    @BindView(R.id.tv_main_title_orderno)
    TextView tvMainTitleOrderno;
    @BindView(R.id.tv_main_title_currentTime)
    public TextView tvMainTitleCurrentTime;
    @BindView(R.id.ll_main_title_suspend_order_info)
    public LinearLayout llMainTitleSuspendOrder;//挂单布局
    @BindView(R.id.tv_main_title_suspend_order_info)
    public TextView tvMainTitleSuspendOrder;//挂单个数
    @BindView(R.id.iv_main_project_logo)
    ImageView ivMainProjectLogo;
    @BindView(R.id.tv_main_member_name)
    TextView tvMainMemberName;
    @BindView(R.id.tv_main_member_cent)
    TextView tvMainMemberCent;
    @BindView(R.id.btn_main_back_to_login)
    Button btnMainBackToLogin;
    @BindView(R.id.btn_main_other_funtion)
    Button btnMainOtherFuntion;
    @BindView(R.id.btn_main_exit_system)
    Button btnMainExitSystem;
    @BindView(R.id.current_good_name)
    TextView currentGoodName;
    @BindView(R.id.current_good_price)
    TextView currentGoodPrice;
    @BindView(R.id.tv_main_dept_name_code)
    TextView tvMainDeptNameCode;
    @BindView(R.id.tv_main_yyy_name_code)
    TextView tvMainYyyNameCode;
    @BindView(R.id.rv_main_goodList)
    RecyclerView lvMainGoodList;
    @BindView(R.id.tv_main_goods_totalNum)
    TextView tvMainGoodsTotalNum;
    @BindView(R.id.tv_main_goods_totalAmt)
    TextView tvMainGoodsTotalAmt;
    @BindView(R.id.tv_main_pay_totalAmt)
    TextView tvMainPayTotalAmt;
    @BindView(R.id.tv_main_pay_preferentialAmt)
    TextView tvMainPayPreferentialAmt;
    @BindView(R.id.tv_main_pay_payableAmt)
    TextView tvMainPayPayableAmt;
    @BindView(R.id.btn_main_pay)
    Button btnMainPay;
    @BindView(R.id.rv_main_select_goodList)
    RecyclerView lvMainSelectGoodList;
    @BindView(R.id.main_input_sfNum_keyBoard)
    SelfNumKeyView mainInputSfNumKeyBoard;//自定义软键盘
    @BindView(R.id.ll_main_memberInfo)
    LinearLayout llMainMemberInfo;//会员信息布局
    @BindView(R.id.ll_main_current_input_goodInfo)
    LinearLayout llMainCurrentInputGoodInfo;//当前录入商品布局
    @BindView(R.id.et_main_soft_keyboard)
    EditText etMainSoftKeyboard;//录入框
    @BindView(R.id.tv_main_ordet_type_name)
    TextView tvOrderType;//订单类型

    private final MyHandler handler = new MyHandler(this);

    public SalePresenterImpl mSalePresenterImpl;
    public TicketInfo mTicketInfo;  //小票
    private List<Goods> saleGoods;//商品临时列表
    private List<Goods> defaultGoods;//默认商品集合
    private Goods tempGoods;
    private DefaultGoodAdapter defaultGoodAdapter;  //默认商品适配器
    private GoodsListAdapter mGoodsListAdapter;  // 商品列表适配器
    private ExchangeGoodBillInfoListAdapter exchangeAdapter;  //满赠
    private ProgressDialog mProgressDialog;//等待框
    private AdPresentationUtil adPresentationUtil;
    private List<PromationoodInfo> promationoodInfosList;
    private List<PromationoodInfo> exchangeGoodBillInfoList;
    private List<PromationoodInfo> giftGoodsBillList;
    private int promotionGoodsSelectSign = 0;
    public boolean selectGiftGoods = false;//是否选择过买赠

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        defaultGoods = new ArrayList<>();
        saleGoods = new ArrayList<>();
        promationoodInfosList = new ArrayList<>();
        exchangeGoodBillInfoList = new ArrayList<>();
        giftGoodsBillList = new ArrayList<>();
        initTicket();
        setAdPresentation(0);
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCancelable(false);
        mSalePresenterImpl = new SalePresenterImpl(this);
        tvMainTitleVersion.setText(CommonUtils.getCurrentVersionName(MainActivity.this));
        tvMainTitleCashier.setText(ErpCommonData.loadConfig.getCashierName() + "");
        tvMainTitleSktno.setText(ErpCommonData.sktno + "");
        tvMainTitleOrderno.setText(ErpCommonData.orderNo + "");
        Picasso.get().load(R.mipmap.shiji_log1).
                networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
                .placeholder(R.mipmap.shiji_log1).error(R.mipmap.shiji_log1)
                .into(ivMainProjectLogo);
        TimeThread timeThread = new TimeThread(handler,Constant.MAIN_UPDATE_CURRENT_TIME_HANDLEID);
        timeThread.setDaemon(true);//守护线程
        timeThread.start();

        initDeptAndYYY();

        defaultGoods.clear();
        defaultGoods.addAll(ErpCommonData.loadConfig.getGoodsList());
        defaultGoodAdapter = new DefaultGoodAdapter(R.layout.item_sale_defaultgoods, defaultGoods, this); //默认商品

        exchangeAdapter = new ExchangeGoodBillInfoListAdapter(R.layout.item_sale_giftgoods,promationoodInfosList,this);
        lvMainSelectGoodList.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));
        lvMainSelectGoodList.setAdapter(defaultGoodAdapter);
        defaultGoodAdapter.setNewData(defaultGoods);
        defaultGoodAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (ErpCommonData.proType == 2) {//收款员登录
                    if(etMainSoftKeyboard.getHint().equals(ConstantString.MAIN_GOOD_CODE)){
                        QueryGoodParam param = new QueryGoodParam();
                        param.setBarcode(defaultGoods.get(position).getBarCode());
                        param.setCount("1");
                        mSalePresenterImpl.queryGoods(param, mTicketInfo,mTicketInfo.getSubTickets().size()-1);
                    }else if(etMainSoftKeyboard.getHint().equals(ConstantString.MAIN_YYY_CODE)){
                        ToastUtils.show("请输入营业员代码！");
                    }else if(etMainSoftKeyboard.getHint().equals(ConstantString.MAIN_GOOD_PRICE)){
                        ToastUtils.show("请输入上一个商品价格！");
                    }
                } else {
                    QueryGoodParam param = new QueryGoodParam();
                    param.setBarcode(defaultGoods.get(position).getBarCode());
                    param.setCount("1");
                    mSalePresenterImpl.queryGoods(param, mTicketInfo,mTicketInfo.getSubTickets().size()-1);
                }
//                mSalePresenterImpl.queryGoods(defaultGoods.get(position).getBarCode(), mTicketInfo);

            }
        });

        mGoodsListAdapter = new GoodsListAdapter(R.layout.item_sale_goods, saleGoods, this);
        lvMainGoodList.setLayoutManager(new GridLayoutManager(getApplicationContext(), 1));
        lvMainGoodList.setAdapter(mGoodsListAdapter);
        DividerItemDecoration mDividerItemDecoration = new DividerItemDecoration(MainActivity.this, DividerItemDecoration.VERTICAL);
        mDividerItemDecoration.setDrawable(new ColorDrawable(ContextCompat.getColor(MainActivity.this, R.color.main_good_info_bar)));
        lvMainGoodList.addItemDecoration(mDividerItemDecoration);

        mGoodsListAdapter.setNewData(saleGoods);

        CommonUtils.setNoSoftware(etMainSoftKeyboard, MainActivity.this, true);
        mainInputSfNumKeyBoard.setEnterReceptor(etMainSoftKeyboard);
        resetKeyboardHint();
        mainInputSfNumKeyBoard.setOnCallBack(this);
        btnMainBackToLogin.setOnClickListener(new FunctionOnClickListener());
        btnMainOtherFuntion.setOnClickListener(new FunctionOnClickListener());
        btnMainExitSystem.setOnClickListener(new FunctionOnClickListener());
        btnMainPay.setOnClickListener(new FunctionOnClickListener());

        mSalePresenterImpl.createSaleId("");

        if(SDTools.traverseFolderPick().size()>0){//是否有挂单记录
            llMainTitleSuspendOrder.setVisibility(View.VISIBLE);
            tvMainTitleSuspendOrder.setText(SDTools.traverseFolderPick().size()+"");
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.d("onStart()方法");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        mTicketInfo = ErpCommonData.ticketInfo;
        LogUtils.d("onRestart()方法");
        addGoodsToTicket(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.d("onResume()方法");
        if(mTicketInfo.isDJD()){//生成订金单
            tvOrderType.setVisibility(View.VISIBLE);
            tvOrderType.setText(ConstantString.MAIN_ORDER_TYPE_DEPOSIT);
            tvMainTitleOrderno.setText(ErpCommonData.orderNo + "");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.d("onPause()方法");
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.d("onStop()方法");
    }

    private void initDeptAndYYY() {
        int subInx = mTicketInfo.getSubTickets().size() - 1;
        Person currentYYY = mTicketInfo.getSubTickets().get(subInx).getPersonInfo();
        tvMainDeptNameCode.setText(currentYYY.getPersonDeptName() + "【" + currentYYY.getPersonDeptCode() + "】");
        tvMainYyyNameCode.setText(currentYYY.getPersonName() + "【" + currentYYY.getPersonCode() + "】");
    }

    private void resetKeyboardHint() {
        if (ErpCommonData.proType == 2){
            mainInputSfNumKeyBoard.setIsCanInputPoint(false);
            bindTvspCode(ConstantString.MAIN_YYY_CODE);
        } else {
            mainInputSfNumKeyBoard.setIsCanInputPoint(false);
            bindTvspCode(ConstantString.MAIN_GOOD_CODE);
        }
        mainInputSfNumKeyBoard.clearReceptorText();
    }

    private void initTicket() {
        mTicketInfo = ErpCommonData.ticketInfo;
        mTicketInfo.setOrderNo("");
        mTicketInfo.setSktno(ErpCommonData.sktno);
        mTicketInfo.setStoreCode(ErpCommonData.storeCode);
        Person person = new Person();
        person.setPersonCode(ErpCommonData.loadConfig.getCashierCode());
        person.setPersonId(Integer.valueOf(ErpCommonData.loadConfig.getCashierId()));
        person.setPersonName(ErpCommonData.loadConfig.getCashierName());
        person.setPersonDeptCode(ErpCommonData.loadConfig.getCashierDeptCode());
        person.setPersonDeptId(Integer.valueOf(ErpCommonData.loadConfig.getCashierDeptId()));
        person.setPersonDeptName(ErpCommonData.loadConfig.getCashierDeptName());
        person.setShopId(0);
        SubTicketItem subTicketItem = new SubTicketItem();
        subTicketItem.setSubInx("0");
        subTicketItem.setPersonInfo(person);
        mTicketInfo.getSubTickets().clear();
        mTicketInfo.getSubTickets().add(subTicketItem);
        mTicketInfo.setCasherInfo(person);
//        ErpCommonData.isFSTH = false;
//        ErpCommonData.isDJD = false;
        showOrderTotalInfo();
    }

    private void showOrderTotalInfo() {
        double totalNum = 0;
        int totalPrice = 0;
        int totalDiscount = 0;
        for (SubTicketItem sub : mTicketInfo.getSubTickets()) {
            totalPrice += sub.getTotalMoney();
            totalDiscount += sub.getTotalDiscount();
            for (Goods g : sub.getGoodsList()) {
                totalNum += MoneyUtils.getStrToDouble(g.getSaleCount());
            }
        }
        int payableAmt = totalPrice - totalDiscount;
        tvMainGoodsTotalNum.setText("共 " + totalNum + " 件");
        tvMainGoodsTotalAmt.setText(MoneyUtils.getMoneyStr(totalPrice));
        tvMainPayTotalAmt.setText(MoneyUtils.getMoneyStr(totalPrice));
        tvMainPayPreferentialAmt.setText(MoneyUtils.getMoneyStr(totalDiscount));
        tvMainPayPayableAmt.setText(MoneyUtils.getMoneyStr(payableAmt));
    }
    /**
     * 键盘确定按钮事件
     * @param inputStr
     */
    @Override
    public void keyBoardSure(String inputStr,String hint) {
        if (!inputStr.equals("") && inputStr.length() > 0) {
            if (hint.equals(ConstantString.MAIN_YYY_CODE)) {
                mSalePresenterImpl.queryPerson(inputStr,mTicketInfo.getOrderNo());//查询营业员
            } else if (hint.equals(ConstantString.MAIN_GOOD_CODE)) {
                QueryGoodParam param = new QueryGoodParam();
                param.setBarcode(inputStr);
                param.setCount("1");
                mSalePresenterImpl.queryGoods(param, mTicketInfo,mTicketInfo.getSubTickets().size()-1);//查询商品
            } else if (hint.equals(ConstantString.MAIN_GOOD_PRICE)) {
                QueryGoodParam param = new QueryGoodParam();
                param.setGoodsPrice(inputStr);
                param.setCount(tempGoods.getSaleCount());
                param.setBarcode(tempGoods.getBarcode());
                param.setGoodsGuid(tempGoods.getGoodsGuid());
//                inputStr = inputStr + "|" + tempGoods.getSaleCount() + "|" + tempGoods.getBarCode() + "|" + tempGoods.getGoodsGuid();
                mSalePresenterImpl.queryGoods(param, mTicketInfo,mTicketInfo.getSubTickets().size()-1); //查询商品
            }
        } else {
            ToastUtils.show("请输入内容！");
        }
    }

    @Override
    public void showProgress(String msg) {
        mProgressDialog.setMessage(msg);
        mProgressDialog.show();

    }

    @Override
    public void dismissProgress() {
        mProgressDialog.dismiss();
    }

    @Override
    public void loadFail(String msg, int id) {
        switch (id){
            case SalePresenterImpl.QUERYGOODS:{
                SaleUtil.showMsgInto(MainActivity.this,
                        ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                        msg);
            }
            break;
        }
        ToastUtils.show(msg);
    }

    @Override
    public void createOrderNO(String orderNo) {
        ErpCommonData.orderNo = orderNo;
        mTicketInfo.setOrderNo(orderNo);
        tvMainTitleOrderno.setText(ErpCommonData.orderNo + "");
        if(ErpCommonData.isOffline&&ErpCommonData.proType !=2){
            OfflineManager.savePerson(orderNo,ErpCommonData.loadConfig.getCashierId(),ErpCommonData.loadConfig.getCashierDeptId());
        }
    }


    @Override
    public void addPerson(Person person) {
        if(person.getGoodsList()!=null&&person.getGoodsList().size()>0) {
            defaultGoods = person.getGoodsList();
            defaultGoodAdapter.setNewData(defaultGoods);
        }else{
            defaultGoods.clear();
            defaultGoodAdapter.setNewData(defaultGoods);
        }
        //先添加子小票
        int position = mTicketInfo.getSubTickets().size() - 1;
        if(person.getPersonId() == mTicketInfo.getSubTickets().get(position).getPersonInfo().getPersonId()){
           // ToastUtils.show("录入营业员和当前营业员相同请直接录入商品代码！");
            bindTvspCode(ConstantString.MAIN_GOOD_CODE);
        }else{
            if(mTicketInfo.getSubTickets().get(position).getGoodsList().size()>0){
                SubTicketItem subTicketItem = new SubTicketItem();
                subTicketItem.setSubInx(mTicketInfo.getSubTickets().size()+"");
                subTicketItem.setPersonInfo(person);
                mTicketInfo.getSubTickets().add(subTicketItem);

                position = mTicketInfo.getSubTickets().size() - 1;
                mTicketInfo.getSubTickets().get(position).setPersonInfo(person);
                initDeptAndYYY();
                bindTvspCode(ConstantString.MAIN_GOOD_CODE);
            }else{
                mTicketInfo.getSubTickets().get(position).setPersonInfo(person);
                bindTvspCode(ConstantString.MAIN_GOOD_CODE);
            }

        }




    }

    /**
     * 查询商品成功
     * @param goods
     */
    @Override
    public void handleGoods(Goods goods) {
        tempGoods = goods;
        if("1".equals(tempGoods.getClassType()) && (tempGoods.getGoodsGuid()==null || tempGoods.getGoodsGuid().length()<=0||"0".equals(tempGoods.getPrice())))
         {// 大类或细类_需输入售价  && tempGoods.getPrice().equals("0")
            if("商品代码".equals(etMainSoftKeyboard.getHint())) {
                mainInputSfNumKeyBoard.setIsCanInputPoint(true);
                bindTvspCode(ConstantString.MAIN_GOOD_PRICE);
            }else{
                if("1".equals(ErpCommonData.isSaleZero)){
                    addGoodsToTicket(false);
                }else{
                    mainInputSfNumKeyBoard.setIsCanInputPoint(true);
                    bindTvspCode(ConstantString.MAIN_GOOD_PRICE);
                }
            }
        }
        else {
            addGoodsToTicket(false);
        }
    }

    /**
     * 准备付款
     *
     * @param ticketInfo
     */
    /**
     * 准备付款 /预算接口
     * @param ticketInfo
     * @param isPromotion true 预算接口   false  准备付款
     */
    @Override
    public void preparePay(TicketInfo ticketInfo,boolean isPromotion, List<PromationoodInfo> exchangeGoodBillInfoList, List<PromationoodInfo> giftGoodsBillList) {
        if(isPromotion){
            ErpCommonData.ticketInfo = ticketInfo;
            SaleUtil.showOrderPreferentialInto(MainActivity.this,ticketInfo);
        }else{
            if (giftGoodsBillList.size() > 0 || exchangeGoodBillInfoList.size() >0){
                SaleUtil.showPromationoodInfosList(MainActivity.this,exchangeAdapter,exchangeGoodBillInfoList,
                        giftGoodsBillList,ticketInfo,selectGiftGoods);
            }else {
                ErpCommonData.ticketInfo = ticketInfo;
                Bundle bundle = new Bundle();
                if (ticketInfo.isFSTH()) {
                    bundle.putInt("SaleType", 1);
                } else {
                    bundle.putInt("SaleType", 0);
                }
                go2Activity(PayActivity.class, bundle);
                overridePendingTransition(0, 0);
            }
        }
    }

    public void setSelectGiftGoods(boolean selectGiftGoods){
       this.selectGiftGoods = selectGiftGoods;
    }

    @Override
    public void frontDiscount(List<Goods> goods, boolean isSingle) {
        mTicketInfo.getSubTickets().get(mTicketInfo.getSubTickets().size() - 1).setGoodsList(goods);
        saleGoods.clear();
        for(int i = mTicketInfo.getSubTickets().get(mTicketInfo.getSubTickets().size() - 1).getGoodsList().size()-1;i>=0;i--){
            saleGoods.add(mTicketInfo.getSubTickets().get(mTicketInfo.getSubTickets().size() - 1).getGoodsList().get(i).goodClone());
        }
        mGoodsListAdapter.setNewData(saleGoods);
        setAdPresentation(1);
        showOrderTotalInfo();
    }

    @Override
    public void cancelOrder(String orderNo) {
        resetKeyboardHint();
        if (llMainMemberInfo.getVisibility() == View.VISIBLE) {
            llMainMemberInfo.setVisibility(View.GONE);
        }
        ErpCommonData.ticketInfo = new TicketInfo();
        initTicket();
        saleGoods.clear();
        mGoodsListAdapter.setNewData(saleGoods);
        initDeptAndYYY();
        showCurrentGoodInfo();
//        ErpCommonData.isDJD = false;
//        ErpCommonData.isFSTH = false;
        tvOrderType.setVisibility(View.GONE);
        mSalePresenterImpl.createSaleId("");
        setAdPresentation(4);
    }

    @Override
    public void addMember(Member member) {
        if (member == null) {
            mTicketInfo.setMemberInfo(null);
            llMainMemberInfo.setVisibility(View.GONE);
        } else {
            mTicketInfo.setMemberInfo(member);
            llMainMemberInfo.setVisibility(View.VISIBLE);
            if(member.getMemberName()!=null&&!"".equals(member.getMemberName())) {
                tvMainMemberName.setText(member.getMemberName());
            }else{
                if(member.getMemberPhone()!=null&&member.getMemberPhone().length()>4) {
                    tvMainMemberName.setText("手机号:"+member.getMemberPhone().substring(member.getMemberPhone().length()-4,member.getMemberPhone().length()));
                }else{
                    tvMainMemberName.setText("手机号:"+member.getMemberPhone());
                }
            }
            tvMainMemberCent.setText(member.getMemberCardValidCent());
            setAdPresentation(2);
        }
    }

    @Override
    public void onRegisterMemberFailure(final QueryMemberReq memberReq, String err) {
        SaleUtil.showInfoDialog(MainActivity.this,
                "会员",
                err+"，是否注册此会员？",
                new OnDialogListener() {
                    @Override
                    public void onClick(int flag) {
                        if(flag == DialogConstant.DIALOG_BTN_SURE){
                            memberReq.setIsCreate("1");
                            mSalePresenterImpl.queryMember(memberReq);
                        }
                    }
                });
    }


    /**
     *
     * @param isSuspendOrderRefresh 是否是挂单刷新界面
     */
    private void addGoodsToTicket(boolean isSuspendOrderRefresh) {
        ToastUtils.show("操作商品成功");
        mainInputSfNumKeyBoard.setIsCanInputPoint(false);
        bindTvspCode(ConstantString.MAIN_GOOD_CODE);
        mainInputSfNumKeyBoard.clearReceptorText();
        LogUtils.d("当前子小票的长度:" + mTicketInfo.getSubTickets().size());
        boolean isGoods = false;//是否直接添加商品标志
        if(!isSuspendOrderRefresh){
            subFlag:
            for (int i = 0; i < mTicketInfo.getSubTickets().size(); i++) {
                SubTicketItem itemSub = mTicketInfo.getSubTickets().get(i);
                if (itemSub.getGoodsList().size() <= 0) {
                    isGoods = true;
                    itemSub.getGoodsList().add(tempGoods);
                    break;
                }
                for (Goods g : itemSub.getGoodsList()) {
                    if (tempGoods.getGoodsGuid().equals(g.getGoodsGuid())) {
                        isGoods = true;
                        if (tempGoods.getSaleCount().equals("0")) {
                            itemSub.getGoodsList().remove(g);
                            break subFlag;
                        }
                        g.setSaleCount(tempGoods.getSaleCount());
                        g.setSaleMoney(tempGoods.getSaleMoney());
                        g.setDiscount(tempGoods.getDiscount());
                        g.setPreferentialMoney(tempGoods.getPreferentialMoney());
                        break subFlag;
                    }
                }
            }
            if (!isGoods) {
                mTicketInfo.getSubTickets().get(mTicketInfo.getSubTickets().size() - 1).getGoodsList().add(0,tempGoods);
            }
        }
        saleGoods.clear();
        for (int i = mTicketInfo.getSubTickets().size()-1; i >= 0; i--) {
            SubTicketItem item = mTicketInfo.getSubTickets().get(i);
            LogUtils.d("当前子小票商品列表长度:" + item.getGoodsList().size());
            for(int j = 0 ; j < item.getGoodsList().size(); j++){
                saleGoods.add(item.getGoodsList().get(j).goodClone());
            }
        }
        mGoodsListAdapter.setNewData(saleGoods);
        setAdPresentation(1);
        if (llMainCurrentInputGoodInfo.getVisibility() == View.GONE && saleGoods.size() > 0) {
            llMainCurrentInputGoodInfo.setVisibility(View.VISIBLE);
        }
        showCurrentGoodInfo();
        showOrderTotalInfo();
    }

    private void showCurrentGoodInfo() {
        if(ErpCommonData.proType == 2){
            llMainCurrentInputGoodInfo.setVisibility(View.GONE);
        }else {
            if (saleGoods.size() > 0) {
                currentGoodName.setText(saleGoods.get(0).getName());
                currentGoodPrice.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(saleGoods.get(0).getPrice())));
            } else {
                llMainCurrentInputGoodInfo.setVisibility(View.GONE);
            }
        }
    }

    private void bindTvspCode(String hintMsg) {
        etMainSoftKeyboard.setFocusable(true);
        etMainSoftKeyboard.requestFocus();
        mainInputSfNumKeyBoard.setNumKeyBoardHint(hintMsg);
    }

    @Override
    public void doAfterSwipeCard(boolean isSuccess, String content, int handId) {
        LogUtils.d("刷卡的结果为：" + content);
        switch (handId) {
            case Constant.MEMBER_SWIPECARD_HANDLEID: {
                if (isSuccess) {
                    if (!content.equals("")) {
                        QueryMemberReq memberR = new QueryMemberReq();
                        memberR.setCondType(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SWIPE+"");
                        memberR.setCardNo(content);
                        memberR.setOrderNo(ErpCommonData.ticketInfo.getOrderNo());
                        memberR.setStoreCode(ErpCommonData.storeCode);
                        mSalePresenterImpl.queryMember(memberR);
                    } else {
                        ToastUtils.showMsg("刷卡失败，请重试！");
                    }
                } else {
                    ToastUtils.showMsg("取消刷卡");
                }
            }
            break;
            case Constant.MEMBER_SWIPECARD_REGISTER: {
                if (isSuccess) {
                    if (!content.equals("")) {
                        QueryMemberReq memberR = new QueryMemberReq();
                        memberR.setIsCreate("1");
                        memberR.setCondType(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SWIPE+"");
                        memberR.setCardNo(content);
                        memberR.setOrderNo(ErpCommonData.ticketInfo.getOrderNo());
                        memberR.setStoreCode(ErpCommonData.storeCode);
                        mSalePresenterImpl.queryMember(memberR);
                    } else {
                        ToastUtils.showMsg("刷卡失败，请重试！");
                    }
                } else {
                    ToastUtils.showMsg("取消刷卡");
                }
            }
            break;
            default:
                break;
        }
    }

    private class FunctionOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_main_back_to_login://到登录界面切换营业员
                    if(ErpCommonData.ticketInfo.getTicketGoodCount()>0){
                        SaleUtil.showMsgInto(MainActivity.this,
                                ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                                ConstantString.DIALOG_MAIN_SWITCHING_PEOPLE_MESSAGE);
                    }
                    else if(SDTools.traverseFolderPick().size()>0){
                        SaleUtil.showMsgInto(MainActivity.this,
                                ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                                ConstantString.DIALOG_MAIN_SUSPEND_ORDER_SWITCHING_PEOPLE_MESSAGE);
                    }
                    else{
                        ErpCommonData.ticketInfo = new TicketInfo();
                        Intent intentLogin = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intentLogin);
                        finish();
                    }
                    break;
                case R.id.btn_main_other_funtion:
                    Intent intent = new Intent(MainActivity.this, MorefunctionActivity.class);
                    startActivityForResult(intent, Constant.MAIN_TO_MORE_FUNCTION_REQID);
                    break;
                case R.id.btn_main_exit_system://退出系统
                    SaleUtil.showInfoDialog(MainActivity.this,
                            ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                            ConstantString.DIALOG_MAIN_EXIST_SYSTEM_MESSAGE,
                            new OnDialogListener() {
                                @Override
                                public void onClick(int flag) {
                                    if(flag == DialogConstant.DIALOG_BTN_SURE){

//                                        mSalePresenterImpl.cancelOrder(mTicketInfo.getOrderNo());
                                        if(ErpCommonData.ticketInfo.getTicketGoodCount()>0){
                                            SaleUtil.showMsgInto(MainActivity.this,
                                                    ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                                                    ConstantString.DIALOG_MAIN_SWITCHING_PEOPLE_MESSAGE);
                                        }
                                        else if(SDTools.traverseFolderPick().size()>0){
                                            SaleUtil.showMsgInto(MainActivity.this,
                                                    ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                                                    ConstantString.DIALOG_MAIN_SUSPEND_ORDER_SWITCHING_PEOPLE_MESSAGE);
                                        }
                                        else{

                                            PosHttpManager.LoginOut(new OkHttpUtils.ResultCallback() {
                                                @Override
                                                public void onSuccess(JsonObject response) {

                                                    APApplication.getInstance().exit();

                                                }
                                                @Override
                                                public void onFailure(String msg) {
                                                }
                                            });

                                        }
                                    }
                                }
                            });
                    break;
                case R.id.btn_main_pay:
                    if(mTicketInfo.isDJD())
                        SaleUtil.showDepositInputInfoDialog(MainActivity.this,mTicketInfo);
                    else{
                        selectGiftGoods = false;
                        exchangeGoodBillInfoList.clear();
                        giftGoodsBillList.clear();
                        if(ErpCommonData.isOffline) {
                            upLoadGoodsPreparePay(false, exchangeGoodBillInfoList, giftGoodsBillList, promotionGoodsSelectSign);//先调用预算接口      银行
                        }else {
                            upLoadGoodsPreparePay(true, exchangeGoodBillInfoList, giftGoodsBillList, promotionGoodsSelectSign);//先调用预算接口      银行
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    }


    /**
     *
     * @param isPromotion 是否是调用预算接口
     */
    public void upLoadGoodsPreparePay(boolean isPromotion, List<PromationoodInfo> exchangeGoodBillInfoList, List<PromationoodInfo> giftGoodsBillList, int promotionGoodsSelectSign) {
        if (mTicketInfo.getSubTickets() == null || mTicketInfo.getTicketGoodCount() <= 0) {
            ToastUtils.showMsg("请先添加商品");
            return;
        }
        if (mainInputSfNumKeyBoard.getNumKeyBoardHint().equals("价格")) {
            ToastUtils.showMsg("请录入价格");
            return;
        }
        if (ErpCommonData.loadConfig.getPayList() == null || ErpCommonData.loadConfig.getPayList().size() <= 0) {
            ToastUtils.showMsg("此款台没有收款方式，请查看后重新录入！");
            return;
        }
        mSalePresenterImpl.preparePay(mTicketInfo,  isPromotion,exchangeGoodBillInfoList,giftGoodsBillList,promotionGoodsSelectSign);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Constant.MAIN_TO_MORE_FUNCTION_REQID: {
                switch (resultCode) {
                    case Constant.MORE_FUNCTION_TO_MAIN_CANCEL_TRADE_RETID://整单取消
                        SaleUtil.showInfoDialog(MainActivity.this,
                                ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                                ConstantString.DIALOG_MAIN_WHOLE_ORDER_CANCEL_MESSAGE,
                                new OnDialogListener() {
                                    @Override
                                    public void onClick(int flag) {
                                        if(flag == DialogConstant.DIALOG_BTN_SURE){
                                            mSalePresenterImpl.cancelOrder(mTicketInfo.getOrderNo());
                                        }
                                    }
                                });
                        break;
                    case Constant.MORE_FUNCTION_TO_MAIN_ADD_MEMBER_RETID://添加会员
                        PayUtil.showQueryMemberDialog(MainActivity.this, Constant.MEMBER_IDENTIFYING_TRADE_ADD_MEMBER);
                        break;
                    case Constant.MORE_FUNCTION_TO_MAIN_REGISTER_MEMBER_RETID://注册会员
                        PayUtil.showQueryMemberDialog(MainActivity.this, Constant.MEMBER_IDENTIFYING_TRADE_REGISTER_MEMBER);
                        break;
                    case Constant.MORE_FUNCTION_TO_MAIN_FULL_ORDER_DISCOUNT://整单折扣
                        handleFullOrderDiscount();
                        break;
                    case Constant.MORE_FUNCTION_TO_MAIN_ADD_SUB_TICKET://添加子小票功能
                        if(etMainSoftKeyboard.getHint().equals(ConstantString.MAIN_GOOD_PRICE)){
                            ToastUtils.show("请先输入当前商品价格！");
                        }else{
                            ToastUtils.show("请在右下软键盘中录入营业员代码！");
                            bindTvspCode(ConstantString.MAIN_YYY_CODE);
                        }
                        break;
                    case Constant.MORE_FUNCTION_TO_MAIN_NEGATIVE_RETRUN://负数退货
                        if(mTicketInfo.getTicketGoodCount()>0){
                            ToastUtils.show("请先点击负数退货,然后再录入商品");
                        }else{
                            tvOrderType.setVisibility(View.VISIBLE);
                            tvOrderType.setText(ConstantString.MAIN_ORDER_TYPE_NEGATIVE_RETRUN);
                            mTicketInfo.setFSTH(true);
                            mSalePresenterImpl.createSaleId("1");
                        }
                        break;
                    case Constant.MORE_FUNCTION_TO_MAIN_SUSPEND_ORDER://挂单
                        if(mTicketInfo.getTicketGoodCount() <=0){
                            SaleUtil.showMsgInto(MainActivity.this,
                                    ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                                    ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_MESSAGE);
                        }else{
                            SaleUtil.showInfoDialog(MainActivity.this,
                                    ConstantString.DIALOG_MAIN_SUSPEND_ORDER_TITLE,
                                    ConstantString.DIALOG_MAIN_SUSPEND_ORDER_MESSAGE,
                                    new OnDialogListener() {
                                        @Override
                                        public void onClick(int flag) {
                                            if(flag == DialogConstant.DIALOG_BTN_SURE){
                                                if(SDTools.traverseFolderPick().size()<MoneyUtils.getInt(ErpCommonData.gqSum)) {
                                                    SDTools.writeTicketPick(ErpCommonData.ticketInfo, ErpCommonData.ticketInfo.getOrderNo(), new SaveHangUpCallBack() {
                                                        @Override
                                                        public void onSuccess(String time) {
                                                            llMainTitleSuspendOrder.setVisibility(View.VISIBLE);
                                                            LogUtils.d("当地挂单个数为：" + SDTools.traverseFolderPick().size());
                                                            tvMainTitleSuspendOrder.setText(SDTools.traverseFolderPick().size() + "");//展示挂单条数
                                                            ErpCommonData.ticketInfo = null;
                                                            ErpCommonData.ticketInfo = new TicketInfo();
                                                            ErpCommonData.ticketInfo.getSubTickets().clear();
                                                            initTicket();
                                                            addGoodsToTicket(true);


                                                            if (ErpCommonData.uspendPrint.equals("1")){
                                                                List<String> list = TicketFormat.createGuaDanTicket(mTicketInfo.getOrderNo());
                                                                PrintManagerLib.initPrinter(MainActivity.this, CommonUtils.getSystemModel())
                                                                        .initDevice()
                                                                        .printList(list);
                                                            }
                                                            mSalePresenterImpl.createSaleId("");// 更新订单号
                                                        }

                                                        @Override
                                                        public void onFailed(String msg) {
                                                            if (msg != null && msg.length() > 0)
                                                                ToastUtils.show(msg);

                                                        }
                                                    });

                                                }else{
                                                    ToastUtils.show("超过最大挂起笔数"+ErpCommonData.gqSum);
                                                }
                                            }
                                        }
                                    });
                        }
                            break;
                    case Constant.MORE_FUNCTION_TO_MAIN_PICK_HANGUP_TRADE://取单
                        if(SDTools.traverseFolderPick().size()<=0){
                            llMainTitleSuspendOrder.setVisibility(View.GONE);
                        }else{
                            tvMainTitleSuspendOrder.setText(SDTools.traverseFolderPick().size()+"");
                        }
                        mTicketInfo = ErpCommonData.ticketInfo;
                        addGoodsToTicket(true);
                        break;
                    case Constant.BMQ_SCAN_MEMBER://会员扫码
                        Bundle extras = data.getExtras();
                        String content = extras.getString("Code");
                        QueryMemberReq memberR = new QueryMemberReq();
                        memberR.setCondType(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SCAN+"");
                        memberR.setCardNo(content);
                        memberR.setOrderNo(ErpCommonData.ticketInfo.getOrderNo());
                        memberR.setStoreCode(ErpCommonData.storeCode);
                        mSalePresenterImpl.queryMember(memberR);
                        break;
                    case Constant.BMQ_SCAN_REGISTER_MEMBER://注册会员扫码
                        Bundle extras1 = data.getExtras();
                        String content1 = extras1.getString("Code");
                        QueryMemberReq memberR1 = new QueryMemberReq();
                        memberR1.setIsCreate("1");
                        memberR1.setCondType(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SCAN+"");
                        memberR1.setCardNo(content1);
                        memberR1.setOrderNo(ErpCommonData.ticketInfo.getOrderNo());
                        memberR1.setStoreCode(ErpCommonData.storeCode);
                        mSalePresenterImpl.queryMember(memberR1);
                        break;
                    case Constant.MORE_FUNCTION_TO_MAIN_PRINT_FLOWER://印花
                        if (ErpCommonData.proType == 2) {//收款员登录
                            if(etMainSoftKeyboard.getHint().equals(ConstantString.MAIN_GOOD_CODE)){
                                showPrintFlower();
                            }else if(etMainSoftKeyboard.getHint().equals(ConstantString.MAIN_YYY_CODE)){
                                ToastUtils.show("请输入营业员代码！");
                            }
                        } else {
                            showPrintFlower();
                        }
                        break;
                    default:
                        break;
                }
            }
            break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 整单折扣
     */
    private void handleFullOrderDiscount() {
        if (mTicketInfo.getSubTickets() == null || mTicketInfo.getSubTickets().get(0).getGoodsList().size() <= 0) {
            ToastUtils.showMsg("请先添加商品");
        }else{
            int orderTotalMoney =0;
            for(SubTicketItem item : mTicketInfo.getSubTickets()){
                for(Goods g : item.getGoodsList()){
                    orderTotalMoney += MoneyUtils.getMoneyInt(g.getSaleMoney());
                }
            }
            SaleUtil.showFrontDiscountDialog(MainActivity.this,mTicketInfo,orderTotalMoney);
        }
    }

    /**
     * 副显数据
     * @param type
     */
     public void setAdPresentation(int type){
        switch (type){
            case 0:
                adPresentationUtil=new AdPresentationUtil();
                if(adPresentationUtil!=null) {
                    adPresentationUtil.initDisplayData(this);
                }
                break;
            case 1:
                if(adPresentationUtil!=null) {
                    if (adPresentationUtil.getMode() == 0) {
                        adPresentationUtil.setMode(1);
                    }
                    adPresentationUtil.addGoods(saleGoods);
                }
                break;
            case 2:
                if(adPresentationUtil!=null) {
                    adPresentationUtil.addMember(mTicketInfo.getMemberInfo());
                }
                break;
            case 4:
                if(adPresentationUtil!=null) {
                    adPresentationUtil.setMode(0);
                }
                break;
        }
     }

     public void showPrintFlower(){
         InputNumberDialogCommon inputNumberDialogCommon= InputNumberDialogCommon.getInputNumberDialogCommon(MainActivity.this, new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
             @Override
             public void InputDialogOnSubmitClick(String content) {
                 if(content.equals("") || content==null){
                     ToastUtils.showMsg( "输入内容不能为空！");
                     return;
                 }
                 QueryGoodParam param = new QueryGoodParam();
                 param.setBarcode(content);
                 param.setCount("1");
                 param.setStamp("1");
                 mSalePresenterImpl.queryGoods(param, mTicketInfo,mTicketInfo.getSubTickets().size()-1);
             }
         });
         inputNumberDialogCommon.setIsCanInputPoint(false);
         inputNumberDialogCommon.setTitle("印花");
         inputNumberDialogCommon.setContent("请输入印花号");
         inputNumberDialogCommon.setEtHint("印花号");
         inputNumberDialogCommon.showDialog(false);
     }
}
